<?php

namespace App\Admin\Controllers;

use App\Admin\BaseAdmin;
use App\Events\OrderPaySuccess;
use App\Http\Controllers\Controller;
use App\Logic\ConfigLogic;
use App\Models\UserBuyOrder;
use EasyWeChat\Factory;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class UserBuyOrderController extends Controller
{
    use ModelForm, BaseAdmin;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('订单');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(UserBuyOrder::class, function (Grid $grid) {
            $grid->paginate(10);
            $grid->model()->orderByDesc("id");
            $grid->id("ID");
            $grid->order_sn('订单编号')->sortable();
            $grid->user()->name("昵称");
            $grid->column('order_money', '订单金额')->label();
            $grid->column('pay_money', '支付金额')->label();
            $grid->column('order_state', '订单状态')->type_name(UserBuyOrder::ORDER_STATE)->label('default');
            $grid->column('pay_state', '支付状态')->display(function ($s) {
                return $s == 1 ? '<span class="label label-success">已支付</span>' : '<span class="label label-danger">未支付</span>';
            });
            $grid->pay_time('支付时间');
            $grid->pay_sn('支付单号');

            $grid->column('item_type', '订单类型');
            $grid->item()->title('产品名称');
            $grid->l_user()->name('产品用户');

            $grid->column('liveroom_money', '作者分润')->label();
            $grid->column('liveroom_log_id', '流水ID');
            $grid->column('user_buy_id', '购买标识');
            $grid->column('system_money', '系统利润')->label('danger');

            $grid->created_at('下单时间');
            $grid->disableRowSelector();
            $grid->disableCreation();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($actions->row->pay_state == 1) {
                    if ($actions->row->liveroom_log_id == 0 && $actions->row->liveroom_money > 0) {
                        $actions->append('<a href="' . route('user-buy-order-order_action', ['action' => 'fr', 'id' => $actions->getKey()]) . '" class="btn btn-xs btn-success">手动分润</a>');
                    }
                }
                if ($actions->row->pay_state == 0) {
                    if ($actions->row->order_state == 0) {
                        $actions->append('<a href="' . route('user-buy-order-order_action', ['action' => 'ck_pay', 'id' => $actions->getKey()]) . '" class="btn btn-xs btn-default">到账查询</a>');
                        $actions->append('<a href="' . route('user-buy-order-order_action', ['action' => 'close_order', 'id' => $actions->getKey()]) . '" class="btn btn-xs btn-default">关闭订单</a>');
                    }

                }

            });
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->between('pay_time', '支付时间')->datetime();
                $filter->equal('pay_state', '支付状态')->select(['0' => '未支付', '1' => '已支付']);
            });
            $grid->tools(function (Grid\Tools $tools) {
                $tools->disableRefreshButton();
                $tools->append('<div class="btn-group">');
                $tools->append('<a href="' . admin_url('user-buy-order?pay_state=1') . '" class="btn btn-success btn-sm">已支付</a>');
                $tools->append('<a href="' . admin_url('user-buy-order?pay_state=0') . '" class="btn btn-danger btn-sm">未支付</a>');
                $tools->append('</div>');
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(UserBuyOrder::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function order_action(Request $request)
    {
        $id = $request->input("id");
        $action = $request->input("action", "fr");
        $order = UserBuyOrder::query()->findOrFail($id);
        switch ($action) {
            case 'fr':
                if ($order->pay_state != 1) {
                    return $this->error('订单不可操作');
                }
                event(new OrderPaySuccess($order));
                return $this->success('处理完毕');
                break;
            case 'ck_pay':
                if ($order->pay_state != 0) {
                    return $this->error('订单不可操作');
                }
                $app = Factory::payment(ConfigLogic::getWxPayConfig());

                $res = $app->order->queryByOutTradeNumber($order->order_sn);
                if ($res['trade_state'] == 'SUCCESS') {
                    list($state, $msg) = UserBuyOrder::paySuccess($order->order_sn, $res['transaction_id']);
                    if ($state) {
                        return $this->success($res['trade_state_desc']);
                    } else {
                        return $this->error('处理失败');
                    }
                } else {
                    return $this->error($res['trade_state_desc']);
                }
                break;
            case 'close_order':
                if ($order->pay_state != 0) {
                    return $this->error('订单不可操作');
                }
                $app = Factory::payment(ConfigLogic::getWxPayConfig());
                $res = $app->order->close($order->order_sn);
                if ($res['result_code'] == 'SUCCESS') {
                    $order->order_state = UserBuyOrder::ORDER_CLOSE;
                    $order->save();
                    return $this->success('操作成功');
                } else {
                    return $this->success('操作失败');
                }
                break;
        }


    }
}
